﻿using System;
using System.Collections.Generic;
using System.Text;

namespace VkApi
{
    public class VkUtils
    {
        /// <summary>
        /// Parse a fragment to key-value pairs
        /// </summary>
        /// <param name="fragment">Fragment to parse</param>
        /// <returns>Returns a dictionary with keys and values.</returns>
        public static IDictionary<string, string> ParseFragment(string fragment)
        {
            var result = new Dictionary<string, string>();
            if (string.IsNullOrEmpty(fragment))
                return result;

            string[] temp = fragment.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries); //get set of strings like "name=value"
            if (temp.Length == 0)
                return result;
            foreach (string t in temp)
            {
                if (!t.Contains("=")) //if string doesn't contain "=" then skip it
                    continue;
                int equalsPos = t.IndexOf('='); //the position of "=" char
                var key = t.Substring(0, equalsPos);
                var value = t.Substring(equalsPos + 1, t.Length - equalsPos - 1);
                result.Add(key, value);
            }

            return result;
        }

        public static string ToUrlParamString(IDictionary<string, string> parameters)
        {
            var sb = new StringBuilder();
            bool isFirst = true;
            foreach (var p in parameters)
            {
                if (isFirst)
                    isFirst = false;
                else
                    sb.Append('&');
                sb.Append(p.Key);
                sb.Append('=');
                sb.Append(p.Value);
            }

            return sb.ToString();
        }
    }
}
